<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Admin Functions</title>
    <style>
        .message { color: green; }
    </style>
</head>
<body>
<h2>Admin Functions</h2>

<section id="changePasswordSection">
    <h3>Change Own Password</h3>
    <form id="changePasswordForm">
        <label for="newPassword">New Password:</label>
        <input type="password" id="newPassword" name="newPassword" required><br><br>
        <button type="submit">Confirm</button>
    </form>
</section>

<section id="changeCustomerPasswordSection">
    <h3>Change Customer Password</h3>
    <form id="changeCustomerPasswordForm">
        <label for="customerUsername">Customer Username:</label>
        <input type="text" id="customerUsername" name="username" required><br><br>
        <label for="customerNewPassword">New Password:</label>
        <input type="password" id="customerNewPassword" name="newPassword" required><br><br>
        <button type="submit">Confirm</button>
    </form>
</section>

<section id="allCustomersSection">
    <h3>All Customers</h3>
    <button id="fetchCustomers">Fetch Customers</button>
    <table id="customersTable">
        <thead>
        <tr>
            <th>ID</th>
            <th>Username</th>
        </tr>
        </thead>
        <tbody>
        <!-- Customer rows will be populated here -->
        </tbody>
    </table>
</section>

<section id="deleteCustomerSection">
    <h3>Delete Customer</h3>
    <form id="deleteCustomerForm">
        <label for="customerId">Customer ID:</label>
        <label for="customerIdInput"></label><input type="number" id="customerIdInput" name="customerId" required><br><br>
        <button type="submit">Confirm</button>
    </form>
</section>

<section id="findCustomerSection">
    <h3>Find Customer</h3>
    <button id="findByUsername">Find by Username</button>
    <button id="findById">Find by ID</button>

    <div id="findByUsernameDiv" style="display:none;">
        <h4>Find by Username</h4>
        <form id="findByUsernameForm">
            <label for="username">Username:</label>
            <input type="text" id="username" name="username" required><br><br>
            <button type="submit">Search</button>
        </form>
    </div>

    <div id="findByIdDiv" style="display:none;">
        <h4>Find by ID</h4>
        <form id="findByIdForm">
            <label for="customerId">ID:</label>
            <input type="number" id="customerId" name="customerId" required><br><br>
            <button type="submit">Search</button>
        </form>
    </div>




    <div>
        <button id="listProductsBtn">List All Products</button>
        <div id="productsList"></div>
    </div>

    <div>
        <h2>Add New Product</h2>
        <form id="addProductForm">
            <label for="ProductName">Product Name:</label>
            <input type="text" id="ProductName" required>
            <br>
            <label for="manufacturer">Manufacturer:</label>
            <input type="text" id="manufacturer" required>
            <br>
            <label for="model">Model:</label>
            <input type="text" id="model" required>
            <br>
            <label for="purchasePrice">Purchase Price:</label>
            <input type="number" id="purchasePrice" step="0.01" required>
            <br>
            <label for="retailPrice">Retail Price:</label>
            <input type="number" id="retailPrice" step="0.01" required>
            <br>
            <label for="quantity">Quantity:</label>
            <input type="number" id="quantity" required>
            <br>
            <button type="submit">Add Product</button>
            <div id="addProductMessage" class="message"></div>
        </form>
    </div>

    <div>
        <h2>Update Product</h2>
        <form id="updateProductForm">
            <label for="updateProductId">Product ID:</label>
            <input type="number" id="updateProductId" required>
            <br>
            <label for="updateProductName">Product Name:</label>
            <input type="text" id="updateProductName" required>
            <br>
            <label for="updateManufacturer">Manufacturer:</label>
            <input type="text" id="updateManufacturer" required>
            <br>
            <label for="updateModel">Model:</label>
            <input type="text" id="updateModel" required>
            <br>
            <label for="updatePurchasePrice">Purchase Price:</label>
            <input type="number" id="updatePurchasePrice" step="0.01" required>
            <br>
            <label for="updateRetailPrice">Retail Price:</label>
            <input type="number" id="updateRetailPrice" step="0.01" required>
            <br>
            <label for="updateQuantity">Quantity:</label>
            <input type="number" id="updateQuantity" required>
            <br>
            <button type="submit">Update Product</button>
            <div id="updateProductMessage" class="message"></div>
        </form>
    </div>

    <div>
        <h2>Delete Product</h2>
        <form id="deleteProductForm">
            <label for="deleteProductId">Product ID:</label>
            <input type="number" id="deleteProductId" required>
            <br>
            <button type="submit">Delete Product</button>
            <div id="deleteProductMessage" class="message"></div>
        </form>
    </div>



</section>

<script>
    // Change Password
    document.getElementById('changePasswordForm').addEventListener('submit', async function(event) {
        event.preventDefault();
        const newPassword = document.getElementById('newPassword').value;
        try {
            const response = await fetch('http://127.0.0.1:8080/AdminService/updatePassword', {
                method: 'POST',
                headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                body: new URLSearchParams({ newPassword })
            });
            alert(response.ok ? 'Password updated successfully.' : 'Failed to update password.');
        } catch (error) {
            console.error('Error:', error);
            alert('An error occurred. Please try again.');
        }
    });

    // Change Customer Password
    document.getElementById('changeCustomerPasswordForm').addEventListener('submit', async function(event) {
        event.preventDefault();
        const username = document.getElementById('customerUsername').value;
        const newPassword = document.getElementById('customerNewPassword').value;
        try {
            const response = await fetch('http://127.0.0.1:8080/AdminService/changeCustomerPassword', {
                method: 'POST',
                headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                body: new URLSearchParams({ username, newPassword })
            });
            alert(response.ok ? 'Customer password updated successfully.' : 'Failed to update customer password.');
        } catch (error) {
            console.error('Error:', error);
            alert('An error occurred. Please try again.');
        }
    });

    // Fetch All Customers
    document.getElementById('fetchCustomers').addEventListener('click', async function() {
        try {
            const response = await fetch('http://127.0.0.1:8080/AdminService/getAllCustomers');
            const data = await response.json();
            const tableBody = document.getElementById('customersTable').getElementsByTagName('tbody')[0];
            tableBody.innerHTML = '';
            data.forEach(customer => {
                const row = tableBody.insertRow();
                row.insertCell(0).textContent = customer.id;
                row.insertCell(1).textContent = customer.username;
            });
        } catch (error) {
            console.error('Error:', error);
            alert('An error occurred. Please try again.');
        }
    });

    // Delete Customer
    document.getElementById('deleteCustomerForm').addEventListener('submit', async function(event) {
        event.preventDefault();
        const customerId = document.getElementById('customerIdInput').value;
        if (confirm('Are you sure you want to delete this customer?')) {
                fetch(`http://127.0.0.1:8080/AdminService/delCustomer?customerId=${customerId}`, {
                    method: 'DELETE',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                }) .then(response => {
                    if (response.ok) {
                        return response.text();
                    } else {
                        throw new Error('Network response was not ok');
                    }
                })
                    .then(data => {
                        console.log(data); // 处理成功响应
                    })
                    .catch(error => {
                        console.error('There was a problem with your fetch operation:', error);
                    });
        }
    });

    // Toggle Find Customer Forms
    document.getElementById('findByUsername').addEventListener('click', function() {
        document.getElementById('findByUsernameDiv').style.display = 'block';
        document.getElementById('findByIdDiv').style.display = 'none';
    });

    document.getElementById('findById').addEventListener('click', function() {
        document.getElementById('findByIdDiv').style.display = 'block';
        document.getElementById('findByUsernameDiv').style.display = 'none';
    });

    // Find Customer by Username
    document.getElementById('findByUsernameDiv').addEventListener('submit', async function(event) {
        event.preventDefault();
        const username = document.getElementById('username').value;
        try {
            const response = await fetch(`http://127.0.0.1:8080/AdminService/findCustomerByUsername?username=${username}`);
            if (response.ok) {
                const data = await response.json();
                console.log('Customer:', data);
                alert('Customer found.');
            } else {
                console.error('Failed to search:', response.status, response.statusText);
                alert('Failed to search.');
            }
        } catch (error) {
            console.error('Error:', error);
            alert('An error occurred. Please try again.');
        }
    });


    // Find Customer by ID
    document.getElementById('findByIdDiv').addEventListener('submit', async function(event) {
        event.preventDefault();
        const customerId = document.getElementById('customerId').value;
        try {
            const response = await fetch(`http://127.0.0.1:8080/AdminService/findCustomerById?id=${customerId}`);
            const data = await response.json();
            console.log('Customer:', data);
            alert(response.ok ? null : 'Failed to search.');
        } catch (error) {
            console.error('Error:', error);
            alert('An error occurred. Please try again.');
        }
    });
















    // List all products
    document.getElementById('listProductsBtn').addEventListener('click', async function() {
        try {
            const response = await fetch('http://127.0.0.1:8080/AdminService/getAllProduct');
            if (response.ok) {
                const products = await response.json();
                const productsListDiv = document.getElementById('productsList');
                productsListDiv.innerHTML = ''; // Clear previous data
                products.forEach(product => {
                    const productItem = document.createElement('div');
                    productItem.textContent = `ID: ${product.id}, Product Name: ${product.ProductName}`;
                    productsListDiv.appendChild(productItem);
                });
            } else {
                console.error('Failed to fetch products:', response.status, response.statusText);
            }
        } catch (error) {
            console.error('Error:', error);
        }
    });

    // Add new product
    document.getElementById('addProductForm').addEventListener('submit', async function(event) {
        event.preventDefault();

        const ProductName = document.getElementById('ProductName').value;
        const manufacturer = document.getElementById('manufacturer').value;
        const model = document.getElementById('model').value;
        const purchasePrice = parseFloat(document.getElementById('purchasePrice').value).toString();
        const retailPrice = parseFloat(document.getElementById('retailPrice').value).toString();
        const quantity = parseInt(document.getElementById('quantity').value, 10).toString();

        try {
            const response = await fetch('http://127.0.0.1:8080/AdminService/addProduct', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    ProductName: ProductName,
                    manufacturer: manufacturer,
                    model: model,
                    purchasePrice: purchasePrice,
                    retailPrice: retailPrice,
                    quantity: quantity
                })
            });

            const messageDiv = document.getElementById('addProductMessage');
            if (response.ok) {
                messageDiv.textContent = 'Product added successfully.';
                messageDiv.className = 'message';
                document.getElementById('addProductForm').reset(); // Reset form
            } else {
                const message = await response.text();
                messageDiv.textContent = `Failed to add product: ${message}`;
                messageDiv.className = 'error';
            }
        } catch (error) {
            console.error('Error:', error);
            const messageDiv = document.getElementById('addProductMessage');
            messageDiv.textContent = 'An error occurred. Please try again.';
            messageDiv.className = 'error';
        }
    });



    // Update product
    document.getElementById('updateProductForm').addEventListener('submit', async function(event) {
        event.preventDefault();
        const product = {
            id: parseInt(document.getElementById('updateProductId').value, 10),
            productName: document.getElementById('updateProductName').value,
            manufacturer: document.getElementById('updateManufacturer').value,
            model: document.getElementById('updateModel').value,
            purchasePrice: parseFloat(document.getElementById('updatePurchasePrice').value),
            retailPrice: parseFloat(document.getElementById('updateRetailPrice').value),
            quantity: parseInt(document.getElementById('updateQuantity').value, 10)
        };

        try {
            const response = await fetch('http://127.0.0.1:8080/AdminService/updateProduct', {
                method: 'PUT',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(product)
            });

            const messageDiv = document.getElementById('updateProductMessage');
            if (response.ok) {
                messageDiv.textContent = 'Product updated successfully.';
                messageDiv.className = 'message';
            } else {
                const message = await response.text();
                messageDiv.textContent = `Failed to update product: ${message}`;
                messageDiv.className = 'error';
            }
        } catch (error) {
            console.error('Error:', error);
            const messageDiv = document.getElementById('updateProductMessage');
            messageDiv.textContent = 'An error occurred. Please try again.';
            messageDiv.className = 'error';
        }
    });

    // Delete product
    document.getElementById('deleteProductForm').addEventListener('submit', async function(event) {
        event.preventDefault();
        const productId = parseInt(document.getElementById('deleteProductId').value, 10);

        if (confirm('Are you sure you want to delete this product?')) {
            try {
                const response = await fetch(`http://127.0.0.1:8080/AdminService/deleteProduct?id=${productId}`, {
                    method: 'DELETE'
                });

                const messageDiv = document.getElementById('deleteProductMessage');
                if (response.ok) {
                    messageDiv.textContent = 'Product deleted successfully.';
                    messageDiv.className = 'message';
                } else {
                    const message = await response.text();
                    messageDiv.textContent = `Failed to delete product: ${message}`;
                    messageDiv.className = 'error';
                }
            } catch (error) {
                console.error('Error:', error);
                const messageDiv = document.getElementById('deleteProductMessage');
                messageDiv.textContent = 'An error occurred. Please try again.';
                messageDiv.className = 'error';
            }
        }
    });




















</script>
</body>
</html>
